package com.jinzhi.eventresource.controller;


import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.eventresource.main.EventresourceAllocationDO;
import com.jinzhi.eventresource.main.EventresourceAllocationsDO;
import com.jinzhi.eventresource.service.EventresourceAllocationsService;
import com.jinzhi.eventresource.vo.DurationVO;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.resourceLibrary.eventresourceVO.ChildrenPageVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 * <pre>
 * 赛项资源模块子节点配置表
 * </pre>
 * <small> 2024-04-03 14:39:55 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/eventresourceAllocations")
public class EventresourceAllocationsController extends BaseController {
    @Autowired
    private EventresourceAllocationsService eventresourceAllocationsService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;

    @GetMapping()
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String EventresourceAllocations(String parentId, Model model) {
        model.addAttribute("parentId", parentId);
        if (parentId != null && !parentId.equals("")) {
            model.addAttribute("parentId", parentId);
            System.out.println("parentId:---Chapter" + parentId);
        }
        return "eventresource/eventresourceAllocations/eventresourceAllocations";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<Page<EventresourceAllocationsDO>> list(EventresourceAllocationsDO eventresourceAllocationsDTO) {
        // 查询列表数据
        Wrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
        wrapper.like(StrUtil.isNotBlank(eventresourceAllocationsDTO.getTitle()), "title", eventresourceAllocationsDTO.getTitle());
        wrapper.eq(ObjectUtil.isNotNull(eventresourceAllocationsDTO.getType()), "type", eventresourceAllocationsDTO.getType());
        wrapper.eq("allocation_id", eventresourceAllocationsDTO.getAllocationId());
        if (StrUtil.isEmpty(eventresourceAllocationsDTO.getTitle())) {
            wrapper.eq("parent_id", eventresourceAllocationsDTO.getAllocationId());
        }

        wrapper.orderBy("createTime", false);
        Page<EventresourceAllocationsDO> page = eventresourceAllocationsService.selectPage(getPage(EventresourceAllocationsDO.class),
                wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            EventresourceAllocationsDO obj = (EventresourceAllocationsDO) page.getRecords().get(i);
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

//    /**
//     * 迁移
//     * @param eventresourceAllocationsDTO
//     * @return
//     */
//    @ResponseBody
//    @GetMapping("/changeChildren")
////    @RequiresPermissions("jzweb:eventresourceAllocation:add")
//    public Result<Object> changeChildren(EventresourceAllocationsDO eventresourceAllocationsDTO) {
//        // 目录转节点判断目录下是否为空
//        Wrapper<EventresourceAllocationsDO> existWrapper = new EntityWrapper<>();
//        existWrapper.eq("parent_id", eventresourceAllocationsDTO.getId());
//        List<EventresourceAllocationsDO> allocationsDOList = eventresourceAllocationsService.selectList(existWrapper);
//        if (ObjectUtil.isNotEmpty(allocationsDOList)) {
//            return Result.fail("存在子资源节点！");
//        }
//        // 更新
//        EntityWrapper<EventresourceAllocationsDO> updateWrapper = new EntityWrapper<>();
//        updateWrapper.eq("id", eventresourceAllocationsDTO.getId());
//        boolean update = eventresourceAllocationsService.update(eventresourceAllocationsDTO, updateWrapper);
//
//        return Result.ok(update);
//    }

    /**
     * 获取子目录和节点
     *
     * @param eventresourceAllocationsDTO
     * @return
     */
    @ResponseBody
    @GetMapping("/getChildren")
//    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<Page<EventresourceAllocationsDO>> getChildren(EventresourceAllocationsDO eventresourceAllocationsDTO) {
        // 查询列表数据
        Wrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", eventresourceAllocationsDTO.getParentId());
        wrapper.like(ObjectUtil.isNotEmpty(eventresourceAllocationsDTO.getTitle()), "title", eventresourceAllocationsDTO.getTitle());
        wrapper.orderBy("createTime", false);
        Page<EventresourceAllocationsDO> page = eventresourceAllocationsService.selectPage(getPage(EventresourceAllocationsDO.class),
                wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            EventresourceAllocationsDO obj = (EventresourceAllocationsDO) page.getRecords().get(i);
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/listChildren")
//    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String listChildren() {
        return "eventresource/eventresourceAllocations/listChildren";
    }

    @GetMapping("/listChildren/add/{id}")
//    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String addChildren(@PathVariable("id") Long id, Model model) {
        model.addAttribute("id", id);
        return "eventresource/eventresourceAllocations/lcadd";
    }

    @GetMapping("/listChildren/edit/{id}")
    String editChildren(@PathVariable("id") Long id, Model model) {
        EventresourceAllocationsDO eventresourceAllocationsDO = eventresourceAllocationsService.selectById(id);
        if (!Objects.isNull(eventresourceAllocationsDO.getSecond())) {
            eventresourceAllocationsDO.setMileSecond((double) eventresourceAllocationsDO.getSecond() / 1000);
        }
        model.addAttribute("eventresourceAllocations", eventresourceAllocationsDO);
        return "eventresource/eventresourceAllocations/lcedit";
    }

    @GetMapping("/add/{id}")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String add(@PathVariable("id") Long id, Model model) {
        model.addAttribute("allocationId", id);
        return "eventresource/eventresourceAllocations/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String edit(@PathVariable("id") Long id, Model model) {
        EventresourceAllocationsDO eventresourceAllocationsDO = eventresourceAllocationsService.selectById(id);
        if (!Objects.isNull(eventresourceAllocationsDO.getSecond())) {
            eventresourceAllocationsDO.setMileSecond((double) eventresourceAllocationsDO.getSecond() / 1000);
        }
        model.addAttribute("eventresourceAllocations", eventresourceAllocationsDO);
        return "eventresource/eventresourceAllocations/edit";
    }

    @Log("添加赛项资源模块子节点配置表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<String> save(EventresourceAllocationsDO eventresourceAllocations) {
        if (!Objects.isNull(eventresourceAllocations.getMileSecond())) {
            Long second = Math.round(eventresourceAllocations.getMileSecond() * 1000);
            eventresourceAllocations.setSecond(second);
        }

        if (ObjectUtil.isEmpty(eventresourceAllocations.getTitle())) {
            return Result.fail("标题不能为空！");
        }
        if (ObjectUtil.isEmpty(eventresourceAllocations.getType())) {
            return Result.fail("资源类型不能为空！");
        }

        eventresourceAllocations.setCreateTime(new Date());
        UserDO sysUser = ShiroUtils.getSysUser();
        eventresourceAllocations.setCreateBy(sysUser.getUsername());

        // 计算总题库数量
        if (ObjectUtil.isNotNull(eventresourceAllocations.getPaperModule())) {
            List<KnowledgePointsDO> knowssList = knowledgePointsService.knowss(eventresourceAllocations.getPaperModule().toString());
            TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.selectById(eventresourceAllocations.getPaperModule().toString());

            Integer nums = 0;
            for (KnowledgePointsDO knowledgePointsDO : knowssList) {
                EntityWrapper<CertificateNewsDO> wrapper = new EntityWrapper<>();
                wrapper.eq("profile_id", knowledgePointsDO.getProfileId());
                CertificateNewsDO certificateNewsDO = certificateNewsService.selectOne(wrapper);
                /** 证书等级（0高级，1中级，2初级） */
                String grade = "";
                if (certificateNewsDO.getGrade() == 0) {
                    grade = "高级";
                } else if (certificateNewsDO.getGrade() == 1) {
                    grade = "中级";
                } else if (certificateNewsDO.getGrade() == 2) {
                    grade = "初级";
                }

                if (ObjectUtil.equal(certificateNewsDO.getId(), testPaperTemplateDO.getNewsId()) &&
                        ObjectUtil.equal(grade, knowledgePointsDO.getGrade())) {
                    nums += knowledgePointsDO.getJudgeNum0();
                    nums += knowledgePointsDO.getSingleNum0();
                    nums += knowledgePointsDO.getMultipleNum0();
                }
            }
            eventresourceAllocations.setNums(nums);
        }
        try {
//            if (eventresourceAllocations.getType() == 5 || eventresourceAllocations.getType() == 6) {
            // 截取视频第一帧做封面图 1s
            if (ObjectUtil.isNotEmpty(eventresourceAllocations.getMp4url())
                    && ObjectUtil.equal(eventresourceAllocations.getMp4url().substring(eventresourceAllocations.getMp4url().lastIndexOf(".")), ".mp4")) {
                String imgUrl = eventresourceAllocations.getMp4url() + "?x-oss-process=video/snapshot,t_" + eventresourceAllocations.getSecond() + ",f_jpg,w_0,h_0";
                System.out.println(imgUrl);
                eventresourceAllocations.setImgurl(imgUrl);
            }
//            }
            eventresourceAllocationsService.insert(eventresourceAllocations);
        } catch (Exception e) {
            if (e.getMessage().contains("index out of range")) {
                return Result.fail(e.getMessage());
            } else {
                return Result.fail("字数长度限制50字，所属赛项200字!");
            }
        }
        return Result.ok();
    }

    //EntityWrapper<CertificateNewsDO> wrapper = new EntityWrapper<>();
//                wrapper.eq("profile_id", knowledgePointsDO.getProfileId());
//                CertificateNewsDO certificateNewsDO = certificateNewsService.selectOne(wrapper);
//                /** 证书等级（0高级，1中级，2初级） */
//                String grade = "";
//                if (certificateNewsDO.getGrade() == 0) {
//                    grade = "高级";
//                } else if (certificateNewsDO.getGrade() == 1) {
//                    grade = "中级";
//                } else if (certificateNewsDO.getGrade() == 2) {
//                    grade = "初级";
//                }
//
//                if (StringUtils.contains(knowledgePointsDO.getGrade(), grade)) {
//                    try {
//                        nums += knowledgePointsDO.getJudgeNum0();
//                        nums += knowledgePointsDO.getSingleNum0();
//                        nums += knowledgePointsDO.getMultipleNum0();
//                    } catch (Exception e) {
//                        Result.fail(knowledgePointsDO.getName() + "模块存在空题目数量！");
//                    }
//                }
    @Log("修改赛项资源模块子节点配置表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<String> update(EventresourceAllocationsDO eventresourceAllocations) {
        if (Objects.nonNull(eventresourceAllocations.getMileSecond())) {
            Long second = Math.round(eventresourceAllocations.getMileSecond() * 1000);
            eventresourceAllocations.setSecond(second);
        }

        eventresourceAllocations.setUpdateTime(new Date());
        if (ObjectUtil.isEmpty(eventresourceAllocations.getTitle())) {
            return Result.fail("标题不能为空！");
        }
        if (ObjectUtil.isEmpty(eventresourceAllocations.getType())) {
            return Result.fail("资源类型不能为空！");
        }

        // 目录转节点判断目录下是否为空
        Wrapper<EventresourceAllocationsDO> existWrapper = new EntityWrapper<>();
        existWrapper.eq("parent_id", eventresourceAllocations.getId());
        List<EventresourceAllocationsDO> allocationsDOList = eventresourceAllocationsService.selectList(existWrapper);

        EventresourceAllocationsDO allocationsDO = eventresourceAllocationsService.selectById(eventresourceAllocations.getId());
        if (ObjectUtil.isNotEmpty(allocationsDOList) && ObjectUtil.notEqual(allocationsDO.getNodeType(), eventresourceAllocations.getNodeType())) {
            return Result.fail("存在子资源节点！");
        }

        // 修改组别
        eventresourceAllocations.setAllocationsIds(Arrays.asList(eventresourceAllocations.getId().toString()));
        eventresourceAllocationsService.updateGroup(eventresourceAllocations);

        boolean update = true;
        try {
            // 截取视频第一帧做封面图
            if (ObjectUtil.isNotEmpty(eventresourceAllocations.getMp4url())
                    && ObjectUtil.equal(eventresourceAllocations.getMp4url().substring(eventresourceAllocations.getMp4url().lastIndexOf(".")), ".mp4")) {
                String imgUrl = eventresourceAllocations.getMp4url() + "?x-oss-process=video/snapshot,t_" + eventresourceAllocations.getSecond() + ",f_jpg,w_0,h_0";
                System.out.println(imgUrl);
                eventresourceAllocations.setImgurl(imgUrl);
            }
//            }
            update = eventresourceAllocationsService.updateById(eventresourceAllocations);
        } catch (Exception e) {
            if (e.getMessage().contains("index out of range")) {
                return Result.fail(e.getMessage());
            } else {
                return Result.fail("字数长度限制50字!");
            }
        }
        return update ? Result.ok() : Result.fail();
    }

    @Log("批量修改组别")
    @ResponseBody
    @PostMapping("/updateGroup")
    public Result updateGroup(@RequestBody EventresourceAllocationsDO eventresourceAllocationsDO) {
        Boolean success = eventresourceAllocationsService.updateGroup(eventresourceAllocationsDO);
        return Result.ok(success);
    }

    @Log("查询是否有无组别资源")
    @ResponseBody
    @GetMapping("/selectGroup")
    public Result selectGroup() {
        List<EventresourceAllocationsDO> eventresourceAllocationsDOList = eventresourceAllocationsService.selectNoneGroupType();
        return Result.ok(eventresourceAllocationsDOList);
    }

    @Log("删除赛项资源模块子节点配置表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<String> remove(Long id) {
        EventresourceAllocationsDO eventresourceAllocationsDO = eventresourceAllocationsService.selectById(id);
        if (ObjectUtil.isNotEmpty(eventresourceAllocationsDO)) {
            Wrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
            wrapper.eq("parent_id", eventresourceAllocationsDO.getId());
            List<EventresourceAllocationsDO> list = eventresourceAllocationsService.selectList(wrapper);
            if (list.size() != 0) {
                return Result.fail("存在子资源，请先删除子资源!");
            }
        }
        eventresourceAllocationsService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除赛项资源模块子节点配置表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        for (Long id : ids) {
            EventresourceAllocationsDO eventresourceAllocationsDO = eventresourceAllocationsService.selectById(id);
            if (ObjectUtil.isNotEmpty(eventresourceAllocationsDO)) {
                Wrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
                wrapper.eq("parent_id", eventresourceAllocationsDO.getId());
                List<EventresourceAllocationsDO> list = eventresourceAllocationsService.selectList(wrapper);
                if (list.size() != 0) {
                    return Result.fail("存在子资源，请先删除子资源!");
                }
            }
        }

        eventresourceAllocationsService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    // 返回所有没有视频时长的id 和 mp4Url
//    @Log("获取无视频时长子资源")
//    @GetMapping("/mp4Url")
//    @ResponseBody
//    public Result mp4Url() {
//        EntityWrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
//        wrapper.like("mp4url", "%.mp4");
//        wrapper.isNull("duration");
//        List<EventresourceAllocationsDO> eventresourceAllocationsDOList = eventresourceAllocationsService.selectList(wrapper);
//        System.out.println(eventresourceAllocationsDOList.size());
//        List<EventresourceAllocationsDO> limit = eventresourceAllocationsDOList.stream().limit(20).collect(Collectors.toList());
//        return Result.ok(limit);
//
//    }

    // 根据allocationsId存入视频时长
//    @Log("批量修改视频时长")
//    @PostMapping("/updateDuration")
//    @ResponseBody
//    public Result updateDuration(@RequestBody DurationVO durationVO) {
//        List<EventresourceAllocationsDO> allocationsDOList = durationVO.getAllocationsDOList();
//        boolean b = eventresourceAllocationsService.updateBatchById(allocationsDOList);
//        return Result.ok(b);
//    }
}
